<template>
  <div class="audit-case-management">
    <!-- 页面头部 -->
    <header class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">案件管理</h1>
          <p class="page-subtitle">案件审批管理和立案审批详情</p>
        </div>
        <div class="header-actions">
          <el-button @click="refreshData">
            <i class="fas fa-sync-alt mr-2"></i>刷新
          </el-button>
        </div>
      </div>
    </header>

    <!-- 功能标签 -->
    <div class="function-tabs">
      <div class="tabs-nav">
        <div 
          v-for="tab in tabs" 
          :key="tab.key"
          class="tab-item"
          :class="{ active: activeTab === tab.key }"
          @click="setActiveTab(tab.key)"
        >
          <i :class="tab.icon"></i>
          <span>{{ tab.name }}</span>
          <span v-if="tab.count" class="tab-count">{{ tab.count }}</span>
        </div>
      </div>
    </div>

    <!-- 审批案件页面 -->
    <div v-if="activeTab === 'approval'" class="tab-content">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-content">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索案件编号、申请人姓名..."
              size="large"
              clearable
            >
              <template #prefix>
                <i class="fas fa-search"></i>
              </template>
            </el-input>
          </div>
          
          <div class="filter-controls">
            <el-select v-model="filters.status" placeholder="审核状态" clearable>
              <el-option label="待审核" value="pending"></el-option>
              <el-option label="审核中" value="reviewing"></el-option>
              <el-option label="已通过" value="approved"></el-option>
              <el-option label="已拒绝" value="rejected"></el-option>
            </el-select>
            
            <el-select v-model="filters.type" placeholder="案件类型" clearable>
              <el-option label="民事纠纷" value="civil"></el-option>
              <el-option label="劳动争议" value="labor"></el-option>
              <el-option label="合同纠纷" value="contract"></el-option>
              <el-option label="知识产权" value="ip"></el-option>
            </el-select>
            
            <el-button type="primary" @click="applyFilters">筛选</el-button>
            <el-button @click="clearFilters">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 案件列表 -->
      <div class="cases-list-section">
        <div class="cases-table">
          <el-table :data="filteredCases" style="width: 100%" v-loading="loading">
            <el-table-column prop="caseNo" label="案件编号" width="140">
              <template #default="scope">
                <span class="font-medium text-blue-600 cursor-pointer" @click="viewCaseDetail(scope.row)">
                  {{ scope.row.caseNo }}
                </span>
              </template>
            </el-table-column>
            
            <el-table-column prop="title" label="案件名称" width="200"></el-table-column>
            
            <el-table-column prop="applicant" label="申请人" width="100"></el-table-column>
            
            <el-table-column prop="type" label="案件类型" width="120">
              <template #default="scope">
                <el-tag :type="getTypeColor(scope.row.type)">
                  {{ getTypeName(scope.row.type) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="审核状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusColor(scope.row.status)">
                  {{ getStatusName(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="submittedAt" label="提交时间" width="120">
              <template #default="scope">
                {{ formatDate(scope.row.submittedAt) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag :type="getPriorityColor(scope.row.priority)" size="small">
                  {{ getPriorityName(scope.row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="viewCaseDetail(scope.row)">查看</el-button>
                <el-button size="small" type="primary" @click="reviewCase(scope.row)" v-if="scope.row.status === 'pending'">审核</el-button>
                <el-button size="small" type="success" @click="approveCase(scope.row)" v-if="scope.row.status === 'reviewing'">通过</el-button>
                <el-button size="small" type="danger" @click="rejectCase(scope.row)" v-if="scope.row.status === 'reviewing'">拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50]"
              :total="filteredCases.length"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 立案审批详情页面 -->
    <div v-if="activeTab === 'details'" class="tab-content">
      <div class="case-details-section">
        <div class="detail-search">
          <el-input
            v-model="detailSearchKeyword"
            placeholder="请输入案件编号查询详情"
            size="large"
            class="search-input"
          >
            <template #append>
              <el-button @click="searchCaseDetails">查询</el-button>
            </template>
          </el-input>
        </div>
        
        <div v-if="selectedCaseDetail" class="case-detail-card">
          <div class="detail-header">
            <h3>{{ selectedCaseDetail.title }}</h3>
            <el-tag :type="getStatusColor(selectedCaseDetail.status)">
              {{ getStatusName(selectedCaseDetail.status) }}
            </el-tag>
          </div>
          
          <div class="detail-content">
            <div class="detail-grid">
              <div class="detail-item">
                <label>案件编号：</label>
                <span>{{ selectedCaseDetail.caseNo }}</span>
              </div>
              <div class="detail-item">
                <label>申请人：</label>
                <span>{{ selectedCaseDetail.applicant }}</span>
              </div>
              <div class="detail-item">
                <label>案件类型：</label>
                <span>{{ getTypeName(selectedCaseDetail.type) }}</span>
              </div>
              <div class="detail-item">
                <label>提交时间：</label>
                <span>{{ formatDateTime(selectedCaseDetail.submittedAt) }}</span>
              </div>
              <div class="detail-item">
                <label>联系电话：</label>
                <span>{{ selectedCaseDetail.phone }}</span>
              </div>
              <div class="detail-item">
                <label>代理律师：</label>
                <span>{{ selectedCaseDetail.lawyer || '未分配' }}</span>
              </div>
            </div>
            
            <div class="detail-description">
              <label>案件描述：</label>
              <p>{{ selectedCaseDetail.description }}</p>
            </div>
            
            <div class="detail-materials">
              <label>案件材料：</label>
              <div class="materials-list">
                <div v-for="material in selectedCaseDetail.materials" :key="material.id" class="material-item">
                  <i class="fas fa-file-alt"></i>
                  <span>{{ material.name }}</span>
                  <el-button size="small" type="primary" link>下载</el-button>
                </div>
              </div>
            </div>
            
            <div class="detail-timeline">
              <label>审核记录：</label>
              <div class="timeline-list">
                <div v-for="record in selectedCaseDetail.timeline" :key="record.id" class="timeline-item">
                  <div class="timeline-time">{{ formatDateTime(record.time) }}</div>
                  <div class="timeline-content">
                    <strong>{{ record.operator }}</strong> {{ record.action }}
                    <p v-if="record.note">{{ record.note }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div v-else class="empty-state">
          <i class="fas fa-search text-4xl text-gray-400"></i>
          <p class="text-gray-500 mt-4">请输入案件编号查询详情</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AuditCaseManagement',
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const activeTab = ref('approval')
    const searchKeyword = ref('')
    const detailSearchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const selectedCaseDetail = ref(null)
    
    const filters = reactive({
      status: '',
      type: ''
    })
    
    // 标签页配置
    const tabs = [
      { key: 'approval', name: '审批案件', icon: 'fas fa-gavel', count: 12 },
      { key: 'details', name: '立案审批详情', icon: 'fas fa-file-alt' }
    ]
    
    // 模拟案件数据
    const cases = ref([
      {
        id: 1,
        caseNo: 'SH-2024-001',
        title: '交通事故人身损害赔偿案',
        applicant: '王先生',
        phone: '13800138001',
        type: 'civil',
        status: 'pending',
        priority: 'high',
        lawyer: '李律师',
        submittedAt: '2024-01-20 09:30:00',
        description: '2024年1月15日，申请人王先生在某路段发生交通事故，造成人身损害，现申请法律援助处理赔偿事宜。',
        materials: [
          { id: 1, name: '交通事故认定书.pdf' },
          { id: 2, name: '医疗诊断证明.jpg' },
          { id: 3, name: '身份证复印件.jpg' }
        ],
        timeline: [
          { id: 1, time: '2024-01-20 09:30:00', operator: '王先生', action: '提交申请', note: '已提交完整材料' },
          { id: 2, time: '2024-01-20 10:15:00', operator: '系统', action: '自动分配', note: '分配给审核部处理' }
        ]
      },
      {
        id: 2,
        caseNo: 'SH-2024-002',
        title: '劳动合同纠纷案',
        applicant: '李女士',
        phone: '13800138002',
        type: 'labor',
        status: 'reviewing',
        priority: 'medium',
        lawyer: '张律师',
        submittedAt: '2024-01-19 14:20:00',
        description: '申请人李女士与公司存在劳动合同纠纷，涉及工资拖欠和不当解雇问题。',
        materials: [
          { id: 1, name: '劳动合同.pdf' },
          { id: 2, name: '工资条.jpg' }
        ],
        timeline: [
          { id: 1, time: '2024-01-19 14:20:00', operator: '李女士', action: '提交申请' },
          { id: 2, time: '2024-01-19 15:00:00', operator: '审核员A', action: '开始审核', note: '材料完整，进入审核流程' }
        ]
      },
      {
        id: 3,
        caseNo: 'SH-2024-003',
        title: '房屋买卖合同纠纷案',
        applicant: '张先生',
        phone: '13800138003',
        type: 'contract',
        status: 'approved',
        priority: 'low',
        lawyer: '王律师',
        submittedAt: '2024-01-18 11:45:00',
        description: '房屋买卖过程中出现合同履行问题，需要法律援助。',
        materials: [
          { id: 1, name: '房屋买卖合同.pdf' },
          { id: 2, name: '房产证复印件.jpg' }
        ],
        timeline: [
          { id: 1, time: '2024-01-18 11:45:00', operator: '张先生', action: '提交申请' },
          { id: 2, time: '2024-01-18 16:30:00', operator: '审核员B', action: '审核通过', note: '符合立案条件，准予受理' }
        ]
      }
    ])
    
    // 计算属性
    const filteredCases = computed(() => {
      let result = cases.value
      
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter(item =>
          item.caseNo.toLowerCase().includes(keyword) ||
          item.title.toLowerCase().includes(keyword) ||
          item.applicant.toLowerCase().includes(keyword)
        )
      }
      
      if (filters.status) {
        result = result.filter(item => item.status === filters.status)
      }
      
      if (filters.type) {
        result = result.filter(item => item.type === filters.type)
      }
      
      return result
    })
    
    // 方法
    const refreshData = () => {
      ElMessage.success('数据已刷新')
    }
    
    const setActiveTab = (tab) => {
      activeTab.value = tab
    }
    
    const applyFilters = () => {
      currentPage.value = 1
    }
    
    const clearFilters = () => {
      Object.assign(filters, {
        status: '',
        type: ''
      })
      searchKeyword.value = ''
      currentPage.value = 1
    }
    
    const viewCaseDetail = (case_) => {
      selectedCaseDetail.value = case_
      activeTab.value = 'details'
      detailSearchKeyword.value = case_.caseNo
    }
    
    const searchCaseDetails = () => {
      const case_ = cases.value.find(c => c.caseNo === detailSearchKeyword.value)
      if (case_) {
        selectedCaseDetail.value = case_
      } else {
        ElMessage.warning('未找到该案件')
        selectedCaseDetail.value = null
      }
    }
    
    const reviewCase = async (case_) => {
      try {
        await ElMessageBox.confirm('确定要开始审核这个案件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        
        case_.status = 'reviewing'
        ElMessage.success('已开始审核')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const approveCase = async (case_) => {
      try {
        await ElMessageBox.confirm('确定要通过这个案件的审核吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        })
        
        case_.status = 'approved'
        ElMessage.success('审核通过')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const rejectCase = async (case_) => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入拒绝原因', '拒绝审核', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder: '请输入拒绝原因'
        })
        
        case_.status = 'rejected'
        ElMessage.success('已拒绝审核')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('操作失败')
        }
      }
    }
    
    const getTypeColor = (type) => {
      const colorMap = {
        civil: '',
        labor: 'success',
        contract: 'warning',
        ip: 'danger'
      }
      return colorMap[type] || ''
    }
    
    const getTypeName = (type) => {
      const nameMap = {
        civil: '民事纠纷',
        labor: '劳动争议',
        contract: '合同纠纷',
        ip: '知识产权'
      }
      return nameMap[type] || type
    }
    
    const getStatusColor = (status) => {
      const colorMap = {
        pending: 'warning',
        reviewing: 'primary',
        approved: 'success',
        rejected: 'danger'
      }
      return colorMap[status] || ''
    }
    
    const getStatusName = (status) => {
      const nameMap = {
        pending: '待审核',
        reviewing: '审核中',
        approved: '已通过',
        rejected: '已拒绝'
      }
      return nameMap[status] || status
    }
    
    const getPriorityColor = (priority) => {
      const colorMap = {
        high: 'danger',
        medium: 'warning',
        low: 'success'
      }
      return colorMap[priority] || ''
    }
    
    const getPriorityName = (priority) => {
      const nameMap = {
        high: '紧急',
        medium: '一般',
        low: '低'
      }
      return nameMap[priority] || priority
    }
    
    const formatDate = (date) => {
      return dayjs(date).format('YYYY-MM-DD')
    }
    
    const formatDateTime = (date) => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }
    
    return {
      loading,
      activeTab,
      searchKeyword,
      detailSearchKeyword,
      currentPage,
      pageSize,
      selectedCaseDetail,
      filters,
      tabs,
      filteredCases,
      refreshData,
      setActiveTab,
      applyFilters,
      clearFilters,
      viewCaseDetail,
      searchCaseDetails,
      reviewCase,
      approveCase,
      rejectCase,
      getTypeColor,
      getTypeName,
      getStatusColor,
      getStatusName,
      getPriorityColor,
      getPriorityName,
      formatDate,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.audit-case-management {
  padding: 24px;
  background-color: #f9fafb;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  color: #6b7280;
  margin: 0;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 功能标签 */
.function-tabs {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tabs-nav {
  display: flex;
  gap: 8px;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #f8fafc;
  color: #6b7280;
  position: relative;
}

.tab-item:hover {
  background: #e2e8f0;
  color: #374151;
}

.tab-item.active {
  background: #3b82f6;
  color: white;
}

.tab-count {
  background: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 标签页内容 */
.tab-content {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 24px;
}

.filter-content {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-box {
  flex: 1;
  max-width: 400px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

/* 案件列表 */
.cases-list-section {
  margin-bottom: 24px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
  margin-top: 24px;
}

/* 案件详情 */
.case-details-section {
  min-height: 400px;
}

.detail-search {
  margin-bottom: 24px;
}

.search-input {
  max-width: 500px;
}

.case-detail-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 24px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.detail-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.detail-content > * + * {
  margin-top: 24px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #374151;
  min-width: 100px;
}

.detail-item span {
  color: #6b7280;
}

.detail-description {
  margin-bottom: 24px;
}

.detail-description label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.detail-description p {
  color: #6b7280;
  line-height: 1.6;
  margin: 0;
}

.detail-materials {
  margin-bottom: 24px;
}

.detail-materials label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.materials-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.material-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
}

.material-item i {
  color: #6b7280;
}

.detail-timeline label {
  display: block;
  font-weight: 500;
  color: #374151;
  margin-bottom: 12px;
}

.timeline-list > * + * {
  margin-top: 12px;
}

.timeline-item {
  display: flex;
  gap: 16px;
  padding: 12px;
  background: #f8fafc;
  border-radius: 8px;
}

.timeline-time {
  font-size: 12px;
  color: #6b7280;
  min-width: 140px;
}

.timeline-content {
  flex: 1;
}

.timeline-content strong {
  color: #374151;
}

.timeline-content p {
  margin: 4px 0 0 0;
  color: #6b7280;
  font-size: 14px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .audit-case-management {
    padding: 16px;
  }
  
  .tabs-nav {
    justify-content: center;
    flex-wrap: wrap;
  }
}
</style>